<template>
  <div class="cart">
    <!-- 顶部导航 -->

    <main class="main">
      <div class="container">
        <!-- 面包屑 -->
        <nav class="breadcrumb">
          <router-link to="/">首页</router-link>
          <span class="sep">我的购物车</span>
        </nav>

        <h1 class="page-title">我的购物车</h1>

        <div class="layout">
          <!-- 左侧：商品列表 -->
          <section class="product-area">
            <!-- 表头 -->
            <header class="table-header hidden-md">
              <span class="col-5">商品信息</span>
              <span class="col-2 text-center">单价</span>
              <span class="col-2 text-center">数量</span>
              <span class="col-2 text-center">小计</span>
              <span class="col-1 text-center">操作</span>
            </header>

            <!-- 商品行 -->
            <article
              v-for="(item, idx) in products"
              :key="item.id"
              class="product-row"
            >
              <div class="row-inner">
                <!-- 信息 -->
                <div class="col-5 info">
                 <img :src="'http://127.0.0.1:8000/static/' + item.img"
     :alt="item.name" />

                  <div>
                    <h4>{{ item.name }}</h4>
<!--                    <p class="spec">{{ item.spec }}</p>-->
                    <p class="price-sm md-hide">单价: ¥{{ item.price.toFixed(2) }}</p>
                  </div>
                </div>

                <!-- 单价 -->
                <div class="col-2 unit hidden-sm">¥{{ item.price.toFixed(2) }}</div>

                <!-- 数量 -->
                <div class="col-2 qty">
                  <button @click="decrease(idx)"><i class="fa fa-minus"></i></button>
                  <input
                    v-model.number="item.qty"
                    type="number"
                    min="1"
                    @change="validate(idx)"
                  />
                  <button @click="increase(idx)"><i class="fa fa-plus"></i></button>
                </div>

                <!-- 小计 -->
                <div class="col-2 sub hidden-sm">¥{{ (item.price * item.qty).toFixed(2) }}</div>

                <!-- 操作 -->
                <div class="col-1 action">
                  <button @click="remove(item.id)">清除<i class="fa fa-trash-o"></i></button>
                </div>

                <!-- 移动端小计 -->
                <div class="sub-sm md-hide">小计: ¥{{ (item.price * item.qty).toFixed(2) }}</div>
              </div>
            </article>

            <!-- 底部按钮 -->
            <footer class="product-footer">
              <router-link to="/" class="btn-text">
                <i class="fa fa-arrow-left"></i> 继续购物
              </router-link>
              <button class="btn-text danger" @click="clearCart">
                <i class="fa fa-trash-o"></i> 清空购物车
              </button>
            </footer>

            <!-- 为你推荐 -->
            <section class="recommend">
              <h3>为您推荐</h3>
              <div class="recommend-list">
                <div v-for="r in recommend.slice(0,3)" :key="r.id" class="recommend-card">
                  <div class="img-box">
                    <img
        :src="r.image_urls
          ? (r.image_urls[0].startsWith('http') ? r.image_urls[0] : `http://127.0.0.1:8000/static/${r.image_urls[0]}`)
          : ''"
        :alt="r.name"
      />
                    <button class="like" @click="addTofavorite(r)"><i class="fa fa-heart-o"></i></button>
                  </div>
                  <h4>{{ r.name }}</h4>
                  <div class="stars">
                    <i v-for="s in 5" :key="s"
                       :class="s <= r.star ? 'fa fa-star' : (s - 0.5 <= r.star ? 'fa fa-star-half-o' : 'fa fa-star-o')"/>
                  </div>
                  <p class="price">¥{{ r.price.toFixed(2) }}</p>
                  <button class="add-btn" @click="addToCart(r)">加入购物车</button>
                </div>
              </div>
            </section>
          </section>

          <!-- 右侧：订单摘要 -->
          <aside class="summary-area">
            <div class="summary-card">
              <h3>订单摘要</h3>

              <ul class="summary-list">
                <li>
                  <span>商品总价</span>
                  <span>¥{{ totalPrice.toFixed(2) }}</span>
                </li>
                <li>
                  <span>运费</span>
                  <span>¥0.00</span>
                </li>
                <li class="total">
                  <span>合计</span>
                  <span>¥{{ (totalPrice - discount).toFixed(2) }}</span>
                </li>
              </ul>


              <button class="checkout-btn" @click="checkout">结算</button>
              <button class="save-btn" @click="saveCart" :disabled="saving">{{ saving ? '保存中...' : '保存到购物车' }}</button>

              <p class="tips">
                <i class="fa fa-lock"></i> 安全支付 | 全场免运费 | 7天无理由退换
              </p>
            </div>
          </aside>
        </div>
      </div>
    </main>

    <!-- 返回顶部 -->
    <transition name="fade">
      <button v-show="showTop" class="back-top" @click="toTop">
        <i class="fa fa-arrow-up"></i>
      </button>
    </transition>

    <!-- 底部 -->
    <Footer />
  </div>
</template>

<script>
import api from '@/api/request'   // 你的 axios 封装
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'

export default {
  name: 'Cart',
  components: { Header, Footer },
  data() {
    return {
      showTop: false,
      coupon: '',
      products: [],   // 不再写死
      recommend: [
        { id: 3, name: '肯尼亚 AA 咖啡豆',
          product_type: 'coffee', star: 4,
          price: 118, img: 'https://picsum.photos/id/493/200/200' },
      ],
      couponTags: [
        { code: '199-20', text: '满199减20' },
        { code: 'new15', text: '新用户立减15' }
      ],
      discount: 0
    }
  },
  computed: {
    totalPrice() {
      return this.products.reduce((s, p) => s + p.price * p.qty, 0)
    }
  },
  async mounted() {
    window.addEventListener('scroll', this.handleScroll)
    await this.loadCart()          // 拉真实数据
    this.get_recommend()
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    /* 核心：统一拉购物车数据 */
    async loadCart() {
      try {
        const res = await api.get('/cart/my')
        console.log('--- 拿到响应 ---', res)
        // 1. 立即解构，避开 Mock 代理

        console.log(res.data)

        this.products = res.data.map(item => ({
          id: item.id,
          name: item.name,
          price: Number(item.price),
          qty: item.quantity,   // ← 这里
          product_id: item.product_id,
          img: item.img
        }))

      } catch (e) {
        console.error(e)
      }
    },
    async addTofavorite(product) {
      this.isSubmitting = true;
      try {
        await api.post('/favorite/add', {
          product_id: product.id,
          product_type: 'coffee',
        })
        this.$message.success("已成功添加至收藏");
      } catch (e) {
          console.error('完整错误对象:', e);
    let errorMsg = "添加收藏失败，请稍后再试"; // 默认错误提示

    if (e.response?.status === 400 || e.response?.status === 500) {
      // 尝试解析 JSON 或直接使用字符串
      try {
        const data = typeof e.response.data === "string"
          ? JSON.parse(e.response.data)
          : e.response.data;
        errorMsg = data.detail || data.error || errorMsg;
      } catch (parseError) {
        errorMsg = e.response.data || errorMsg;
      }
    }

    this.$message.warning(errorMsg);
  } finally {
    this.isSubmitting = false;
  }
  },
    get_recommend(){
      this.$axios.get('http://127.0.0.1:8000/coffeeProduct/recommend')
      .then(res =>{
        this.recommend = res.data
      })
    },
    async saveCart() {
      this.saving = true
      try {
        // 只提取 id + 最新数量
        const batch = this.products.map(p => ({id: p.id, qty: p.qty}))
        await api.put('/cart/batch', {items: batch})
        this.$message.success('购物车已保存')
      } catch (e) {
        this.$message.error(e?.response?.data?.message || '保存失败')
      } finally {
        this.saving = false
      }
    },
    handleScroll() {
      this.showTop = window.scrollY > 300
    },
    toTop() {
      window.scrollTo({top: 0, behavior: 'smooth'})
    },
    increase(idx) {
      this.products[idx].qty += 1
    },
    decrease(idx) {
      if (this.products[idx].qty > 1) this.products[idx].qty -= 1
    },
    validate(idx) {
      const v = this.products[idx].qty
      if (isNaN(v) || v < 1) this.$set(this.products[idx], 'qty', 1)
    },
    async remove(id) {
      if (!confirm('确定要删除这项商品吗？')) {
        return;
      }

      try {
        // 直接在组件中调用删除接口，不依赖外部封装
        const res = await api.delete('/cart', {
          params: {
            ids: id
          }
        });

        alert(res.message || '删除成功');
        // 重新加载购物车数据，保持与后端同步
        this.loadCart();
        window.location.reload();
      } catch (error) {
        console.error('删除失败:', error);
        alert(error.response?.data?.message || '删除失败');
      }
    },
    async clearCart() {
      if (this.products.length === 0) {
        alert('购物车已为空');
        return;
      }

      if (!confirm('确定要清空购物车吗？')) {
        return;
      }

      try {
        // 获取所有商品id，批量删除
        const ids = this.products.map(item => item.id);
        console.log("这是ids"+ids)
        console.log("这是ids"+ids[0])
        const queryString = ids.map(id => `ids=${id}`).join('&');
        const res = await api.delete(`/cart?${queryString}`);

        alert(res.message || '清空成功');
        this.products = []; // 清空本地列表
        window.location.reload();
      } catch (error) {
        console.error('清空失败:', error);
        alert(error.response?.data?.message || '清空失败');
      }
    },
    async addToCart(product) {

       if (this.$store.getters['user/isVisitor']) {
        this.$store.commit('user/SET_REDIRECT_PATH', this.$route.path);
        return this.$confirm(
                '您还暂未登录，无法购买商品，是否前往登录？',
                '提示',
                {confirmButtonText: '是', cancelButtonText: '否', type: 'warning'}
        ).then(() => {
          this.$router.push('/login');
        }).catch(() => {
          this.$message.info('已取消登录');
        });
      }

      try {
        await api.post('/cart', {
          product_id: product.id,
          product_type: 'coffee',
          quantity: 1
        })
        alert("已成功添加至购物车")
        // 添加成功后重新拉一次购物车
        window.location.reload();
      } catch (e) {
        console.error('422 错误详情：', e.response?.data);
        console.error('添加失败', e);
        alert('加入购物车失败');
      }
    },
checkout() {
  if (this.products.length === 0) {
    this.$message.warning('购物车为空，无法结算')
    return
  }

  // 跳转到订单页面并携带购物车数据
  this.$router.push({
    path: '/order',
    query: {
      cartItems: JSON.stringify(this.products)
    }
  })
}
  }
}
</script>

<style scoped>
/* ========== 基础变量 ========== */
:root {
  --primary: #8b5a2b;
  --dark: #3e2723;
  --light: #f5f5dc;
  --radius: 12px;
  --shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.cart {
  min-height: 100vh;
  background: #f9fafb;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* ========== 面包屑 ========== */
.breadcrumb {
  font-size: 0.875rem;
  color: #6b7280;
  margin-bottom: 1.5rem;
}
.breadcrumb a:hover {
  color: var(--primary);
}
.sep::before {
  content: '\f105';
  font-family: 'FontAwesome';
  margin: 0 0.5rem;
}

/* ========== 标题 ========== */
.page-title {
  font-size: 1.75rem;
  font-weight: 700;
  margin-bottom: 1.5rem;
  color: #111;
}

/* ========== 布局 ========== */
.layout {
  display: grid;
  gap: 1.5rem;
  grid-template-columns: 1fr;
}
@media (min-width: 1024px) {
  .layout {
    grid-template-columns: 2fr 1fr;
  }
}

/* ========== 商品区域 ========== */
.product-area {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 5fr 2fr 2fr 2fr 1fr;
  gap: 1rem;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #f3f4f6;
  font-weight: 600;
  color: #6b7280;
}

.product-row {
  border-bottom: 1px solid #f3f4f6;
}
.product-row:hover {
  background: #fafafa;
}
.row-inner {
  display: grid;
  gap: 1rem;
  padding: 1.5rem;
  grid-template-columns: 1fr;
}
@media (min-width: 768px) {
  .row-inner {
    grid-template-columns: 5fr 2fr 2fr 2fr 1fr;
    align-items: center;
  }
}

.info {
  display: flex;
  gap: 1rem;
}
.info img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: var(--radius);
}
.spec {
  font-size: 0.875rem;
  color: #6b7280;
  margin-top: 0.25rem;
}
.price-sm {
  margin-top: 0.5rem;
  font-size: 0.875rem;
}

.qty {
  display: flex;
  align-items: center;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  width: fit-content;
}
.qty button {
  width: 2rem;
  height: 2rem;
  color: #6b7280;
}
.qty input {
  width: 2.5rem;
  text-align: center;
  border-left: 1px solid #d1d5db;
  border-right: 1px solid #d1d5db;
}

.sub {
  font-weight: 600;
  color: var(--primary);
}
.sub-sm {
  font-weight: 600;
  color: var(--primary);
  text-align: center;
  margin-top: 0.75rem;
}

.action button {
  color: #9ca3af;
}
.action button:hover {
  color: #ef4444;
}

/* ========== 推荐 ========== */
.recommend {
  padding: 1.5rem;
}
.recommend h3 {
  font-weight: 700;
  font-size: 1.125rem;
  margin-bottom: 1rem;
}
.recommend-list {
  grid-template-columns: repeat(2, 1fr);
  gap: 1rem;
}
@media (min-width: 768px) {
  .recommend-list {
    grid-template-columns: repeat(3, 1fr);
  }
}
.recommend-card {
  text-align: center;
}
.img-box {
  position: relative;
}
.img-box img {
  width: 100%;
  height: 10rem;
  object-fit: cover;
  border-radius: var(--radius);
}
.like {
  position: absolute;
  top: 0.25rem;
  right: 0.25rem;
  width: 1.5rem;
  height: 1.5rem;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  font-size: 0.75rem;
  color: #9ca3af;
}
.like:hover {
  background: var(--primary);
  color: #fff;
}
.stars {
  font-size: 0.75rem;
  color: var(--primary);
}
.price {
  font-weight: 700;
  color: var(--primary);
  margin-top: 0.25rem;
}
.add-btn {
  margin-top: 0.5rem;
  width: 100%;
  background: var(--primary);
  color: #fff;
  font-size: 0.75rem;
  border-radius: 0.375rem;
  padding: 0.375rem;
}
.add-btn:hover {
  background: var(--dark);
}

/* ========== 摘要区域 ========== */
.summary-area {
  position: sticky;
  top: 6rem;
}
.summary-card {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  padding: 1.5rem;
}
.summary-card h3 {
  font-weight: 700;
  font-size: 1.125rem;
  margin-bottom: 1rem;
}
.summary-list li {
  display: flex;
  justify-content: space-between;
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}
.total {
  font-weight: 700;
  font-size: 1.125rem;
  color: #111;
  border-top: 1px solid #f3f4f6;
  padding-top: 0.5rem;
}
.discount {
  color: #10b981;
}

.coupon-area {
  margin: 1.5rem 0;
}
.coupon-input {
  display: flex;
}
.coupon-input input {
  flex: 1;
  padding: 0.5rem 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem 0 0 0.375rem;
}
.coupon-input button {
  padding: 0.5rem 0.75rem;
  background: var(--primary);
  color: #fff;
  border-radius: 0 0.375rem 0.375rem 0;
}
.coupon-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}
.tag {
  display: inline-flex;
  align-items: center;
  background: var(--primary);
  color: #fff;
  font-size: 0.75rem;
  padding: 0.25rem 0.5rem;
  border-radius: 9999px;
  cursor: pointer;
}
.tag i {
  margin-left: 0.25rem;
}

.checkout-btn,
.save-btn {
  width: 100%;
  padding: 0.75rem;
  border-radius: 0.375rem;
  font-weight: 600;
}
.checkout-btn {
  background: var(--primary);
  color: #fff;
  margin-bottom: 0.75rem;
}
.checkout-btn:hover {
  background: var(--dark);
}
.save-btn {
  border: 1px solid var(--primary);
  color: var(--primary);
}
.save-btn:hover {
  background: var(--primary);
  color: #fff;
}
.tips {
  font-size: 0.75rem;
  color: #6b7280;
  text-align: center;
  margin-top: 0.75rem;
}

/* ========== 底部按钮 ========== */
.product-footer {
  display: flex;
  justify-content: space-between;
  padding: 1.5rem;
  border-top: 1px solid #f3f4f6;
}
.btn-text {
  display: inline-flex;
  align-items: center;
  color: var(--primary);
  font-size: 0.875rem;
}
.btn-text:hover {
  color: var(--dark);
}
.btn-text.danger:hover {
  color: #ef4444;
}

/* ========== 返回顶部 ========== */
.back-top {
  position: fixed;
  right: 1.5rem;
  bottom: 1.5rem;
  width: 3rem;
  height: 3rem;
  background: var(--primary);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  box-shadow: var(--shadow);
  z-index: 50;
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter,
.fade-leave-to {
  opacity: 0;
}

/* ========== 响应式隐藏工具 ========== */
.hidden-sm {
  display: none;
}
@media (min-width: 768px) {
  .hidden-sm {
    display: block;
  }
  .md-hide {
    display: none;
  }
}
.hidden-md {
  display: none;
}
@media (min-width: 768px) {
  .hidden-md {
    display: grid;
  }
}
/* ========= 为您推荐 卡片样式 ========= */
.recommend {
  padding: 1.5rem;
}
.recommend h3 {
  font-size: 1.125rem;
  font-weight: 700;
  margin-bottom: 1rem;
  color: #111;
}
.recommend-list {
  display: grid;
  gap: 1rem;
  grid-template-columns: repeat(2, 1fr);
}
@media (min-width: 768px) {
  .recommend-list {
    grid-template-columns: repeat(3, 1fr);
  }
}
.recommend-card {
  background: #fff;
  border-radius: 0.75rem;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}
.recommend-card img {
  width: 100%;
  height: 10rem;
  object-fit: cover;
}
.recommend-card h4 {
  font-size: 0.875rem;
  font-weight: 600;
  padding: 0.5rem 0.5rem 0.25rem;
  color: #111;
}
.stars {
  padding: 0 0.5rem;
  font-size: 0.75rem;
  color: var(--primary);
}
.price {
  font-weight: 700;
  font-size: 0.875rem;
  color: var(--primary);
  padding: 0 0.5rem;
}
.add-btn {
  width: calc(100% - 1rem);
  margin: 0.5rem;
  padding: 0.375rem 0;
  background: var(--primary);
  color: #fff;
  font-size: 0.75rem;
  border-radius: 0.375rem;
}
.add-btn:hover {
  background: var(--dark);
}
.img-box {
  position: relative;
}
.like {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  width: 1.5rem;
  height: 1.5rem;
  background: rgba(255, 255, 255, 0.85);
  border-radius: 50%;
  font-size: 0.75rem;
  color: #9ca3af;
}
.like:hover {
  background: var(--primary);
  color: #fff;
}
</style>